{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User added successfully.\n"
     ]
    }
   ],
   "source": [
    "import pymysql\n",
    "from werkzeug.security import generate_password_hash\n",
    "import json\n",
    "with open('../static/config/config.json', encoding='utf-8') as conf:\n",
    "    config = json.load(conf)\n",
    "db_host = config['mysql_url']\n",
    "db_user = config['mysql_user']\n",
    "db_password = config['mysql_password']\n",
    "db_name = config['database']\n",
    " \n",
    "new_username = 'l'\n",
    "new_password_plain = '123' \n",
    "new_role = 'admin'\n",
    " \n",
    "new_password_hash = generate_password_hash(new_password_plain)\n",
    " \n",
    "connection = pymysql.connect(\n",
    "    host=db_host,\n",
    "    user=db_user,\n",
    "    password=db_password,\n",
    "    database=db_name,\n",
    "    charset='utf8mb4', \n",
    "    cursorclass=pymysql.cursors.DictCursor\n",
    ")\n",
    " \n",
    "try:\n",
    "    with connection.cursor() as cursor:\n",
    "        sql = \"\"\"\n",
    "        INSERT INTO t_users (username, password, role)\n",
    "        VALUES (%s, %s, %s)\n",
    "        \"\"\"\n",
    "        values = (new_username, new_password_hash, new_role)\n",
    "        cursor.execute(sql, values)\n",
    "    \n",
    "    connection.commit()\n",
    "    print(\"User added successfully.\")\n",
    "except pymysql.MySQLError as e:\n",
    "    print(f\"Error: {e}\")\n",
    "    connection.rollback()\n",
    "finally:\n",
    "    connection.close()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ame",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
